package todo_app

import (
	"fmt"
	"learning/gooop/saga/mqs/logger"
	"strings"
	"sync"
)

type tMockJSONStore struct {
	rwmutex *sync.RWMutex
	once    sync.Once
	items   []*tJSONData
}

func newMockJSONStore() iJSONStore {
	it := new(tMockJSONStore)
	it.init()
	return it
}

func (me *tMockJSONStore) init() {
	me.rwmutex = new(sync.RWMutex)
	me.items = []*tJSONData{}
}

func (me *tMockJSONStore) Load() {
	me.once.Do(func() {
		me.rwmutex.RLock()
		defer me.rwmutex.RUnlock()

		for _, it := range me.items {
			switch it.Tag {
			case TodoEventClass:
				v := new(TodoEvent)
				e := it.Get(v)
				if e == nil {
					GlobalEventBus.Pub(EventLoadTodoCmd, e)
				}
				break
			}
		}
	})
}

func (me *tMockJSONStore) Append(it *tJSONData) {
	me.rwmutex.Lock()
	defer me.rwmutex.Unlock()

	me.items = append(me.items, it)

	lines := []string{}
	for _, it := range me.items {
		lines = append(lines, fmt.Sprintf("%s", string(it.Content)))
	}
	logger.Logf("tMockJSONStore.items: %s", strings.Join(lines, ", "))
}

var MockJSONStore = newMockJSONStore()
